package models

import (
	"database/sql"
	"gitee.com/ha666/gen_sqlx_code/utils"
	"strings"
)

type ColumnInfo struct {
	OrdinalPosition int
	ColumnName      string
	ColumnNameCase  string
	AutoIncrement   string
	PK              string
	DataType        string
	DataLength      int
	IsNullValue     string
	DefaultValue    string
	ColumnComment   string
}

func GetColumnInfos(table_name string) (column_infos []ColumnInfo, err error) {
	rows, err := mainDB.Query("SELECT OrdinalPosition = a.colorder, ColumnName = a.name , AutoIncrement = CASE  WHEN COLUMNPROPERTY(a.id, a.name, 'IsIdentity') = 1 THEN '√' ELSE '×' END, PK = CASE  WHEN EXISTS ( SELECT 1 FROM sysobjects WHERE xtype = 'PK' AND name IN ( SELECT name FROM sysindexes WHERE indid IN ( SELECT indid FROM sysindexkeys WHERE id = a.id AND colid = a.colid ) ) ) THEN '√' ELSE '×' END , DataType = b.name , DecimalNumber = ISNULL(COLUMNPROPERTY(a.id, a.name, 'Scale'), 0) , IsNullValue = CASE  WHEN a.isnullable = 1 THEN '√' ELSE '×' END , DefaultValue = ISNULL(e.text, ''),ColumnComment = ISNULL(g.[value],'') FROM syscolumns a LEFT JOIN systypes b ON a.xusertype = b.xusertype INNER JOIN sysobjects d ON (a.id = d.id AND d.xtype = 'U' AND d.name <> 'dtproperties') LEFT JOIN syscomments e ON a.cdefault = e.id LEFT JOIN sys.extended_properties g ON a.id = g.major_id AND a.colid = g.minor_id LEFT JOIN sys.extended_properties f ON d.id = f.major_id AND f.minor_id = 0 WHERE d.name =? AND g.class <> 7 ORDER BY a.id, a.colorder", table_name)
	defer rows.Close()
	if err != nil {
		return column_infos, err
	}
	return _ColumnInfoRowsToArray(rows)
}

func _ColumnInfoRowsToArray(rows *sql.Rows) (models []ColumnInfo, err error) {
	for rows.Next() {
		model := ColumnInfo{}
		err = rows.Scan(&model.OrdinalPosition, &model.ColumnName, &model.AutoIncrement, &model.PK, &model.DataType, &model.DataLength, &model.IsNullValue, &model.DefaultValue, &model.ColumnComment)
		if err != nil {
			return models, err
		}
		if len(model.ColumnComment) > 0 {
			model.ColumnComment = strings.Replace(model.ColumnComment, "\r", "", -1)
			model.ColumnComment = strings.Replace(model.ColumnComment, "\n", "", -1)
		}
		model.ColumnNameCase = model.ColumnName
		utils.ToBigHump(&model.ColumnNameCase)
		models = append(models, model)
	}
	return models, err
}
